// subPages/health/consult/consult.js
const app = getApp()
var util =  require('../../../utils/util.js');
var flag = false
Page({

  /**
   * 页面的初始数据
   */
  data: {
    evalList: [{ tempFilePaths: [], imgList: [] }],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    if(options.type && options.item){
      let experts = JSON.parse(options.item)
      that.setData({
        experts: experts,
        type: options.type
      })
      util.setNavBarTitle(that.getTitle(that.data.type))
      // console.log(experts)
    }
    if(app.globalData.userId){
      that.setData({
        userId: app.globalData.userId
      })
    }else{
      app.userIdCallback = userId => {
        if (userId != '') {
          that.setData({
            userId: userId
          });
        }
      }
    }
  },

  //获取标题
  getTitle:function(type){
    var title = ''
    switch (type) {
      case '1':
        title = '咨询'
        break;
      case '2':
        title = '咨询'
        break;
      case '3':
        title = '回复'
        break;
    }
    return title
  },

  bindTextArea:function(e){
    // console.log(e)
    this.setData({
      textArea: e.detail.value
    })
  },

  //添加图片
  joinPicture: function (e) {
    var index = e.currentTarget.dataset.index;
    var evalList = this.data.evalList;
    var that = this;
    var imgNumber = evalList[index].tempFilePaths;
    if (imgNumber.length >= 4) {
      util.showModal('提示','最多上传四张图片')
      return;
    }
    wx.showActionSheet({
      itemList: ["从相册中选择", "拍照"],
      itemColor: "#f7982a",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            that.chooseWxImage("album", imgNumber);
          } else if (res.tapIndex == 1) {
            that.chooseWxImage("camera", imgNumber);
          }
        }
      }
    })
  },

  //选择图片
  chooseWxImage: function (type, list) {
    var img = list;
    var len = img.length;
    var that = this;
    var evalList = this.data.evalList;
    wx.chooseImage({
      count: 4,
      sizeType: ["original", "compressed"],
      sourceType: [type],
      success: function (res) {
        // console.log(res)
        var addImg = res.tempFilePaths;
        var addLen = addImg.length;
        if ((len + addLen) > 4) {
          for (var i = 0; i < (addLen - len); i++) {
            var str = {};
            str.pic = addImg[i];
            img.push(str);
          }
        } else {
          for (var j = 0; j < addLen; j++) {
            var str = {};
            str.pic = addImg[j];
            img.push(str);
          }
        }
        that.setData({
          evalList: evalList
        })
        that.upload(img);
      },
    })
  },

  //删除图片
  clearImg: function (e) {
    var that = this
    var index = e.currentTarget.dataset.index;
    var evalList = that.data.evalList;
    wx.request({
      url: app.globalData.apiUrl +'/Api/First/delete',
      data: {
        file: evalList[0].tempFilePaths[index]
      },
      method: 'get',
      header: {
        'content-type': 'application/json' //默认值
      },
      success: function (res) {
        // console.log(res)
        if(res.data == 1){
          var img = evalList[0].tempFilePaths;
          var img2 = evalList[0].imgList;
          img.splice(index, 1);
          img2.splice(index, 1);          
          that.setData({
            evalList: evalList
          })
        }
      },
      fail: function (res) {
        console.log("失败",res);
      }
    })
  },

  //多张图片上传
  upload: function (path) {
    var that = this;
    var curImgList = [];
    for (var i = 0; i < path.length; i++) {
      wx.showToast({
        icon: "loading",
        title: "正在上传"
      }),
      wx.uploadFile({
        url: app.globalData.apiUrl + '/upload',//接口处理在下面有写
        filePath: path[i].pic,
        name: 'img',
        header: { "Content-Type": "multipart/form-data" },
        formData: {
          douploadpic: '1'
        },
        success: function (res) {
          console.log(res)
          curImgList.push(res.data);
          var evalList = that.data.evalList;
          evalList[0].imgList = curImgList;
          that.setData({
            evalList: evalList
          })
        },
        fail: function (e) {
          util.showModal('提示','上传失败')
          return
        },
        complete: function () {
          wx.hideToast();  //隐藏Toast
        }
      })
    }
  },

  //设置图片
  setImg:function(evalList){
    var that = this 
    var imgPort = [];//图片地址，多张以逗号分割
    if(evalList){
      var imgList = evalList[0].imgList
      for (var j = 0; j < imgList.length; j++) {
        imgPort.push(imgList[j])
      }
    }
    // console.log(imgPort)
    return imgPort
  },

  //咨询历史
  // historyBtn:function(){
  //   if(!this.data.experts)return
  //   wx.navigateTo({
  //     url: '../consultHistory/consultHistory?type=' + 1 + '&item=' + JSON.stringify(this.data.experts)
  //   })
  // },

  //提交按钮
  consultBtn:function(){
    var that = this
    if(flag){
      return
    }
    flag = true
    var arr = {}
    if(that.data.type == '3'){
      if(!that.data.textArea){
        util.showModal('提示','请填写您要回复的内容')
        flag = false
        return
      }
      //回复
      arr = {
        expert_tall_id: that.data.experts.id,
        user_id: that.data.experts.user_id,
        expert_id: that.data.experts.expert_id,
        content: that.data.textArea,
        img: that.setImg(that.data.evalList),
        date: util.formatTime(new Date()),
        date_time: (new Date(util.formatTime(new Date())).getTime()) / 1000,
        status: 0
      }
      let pro = JSON.stringify(arr)
      // console.log(pro)
      util.postAjax(app.globalData.apiUrl +'/admin_add_community_health_expert_tall_hf',function(res){
        // console.log(res)
        if(res.data == 1){
          util.showToast('提交成功','success',2000)
          setTimeout(function(){
            wx.navigateBack({
              delta: 1, // 回退前 delta(默认为1) 页面
            })
            flag = false
          },500)
        }else{
          flag = false
          util.showToast('提交失败，请重试','none',2000)
        }
      },{pro: pro})
    }else{
      if(!that.data.textArea){
        util.showModal('提示','请填写您要咨询的问题')
        flag = false
        return
      }
      //咨询
      arr = {
        user_id: that.data.experts.user_id,
        expert_id: that.data.type=='1'?that.data.experts.id:that.data.experts.expert_id,
        content: that.data.textArea,
        img: that.setImg(that.data.evalList),
        date: util.formatTime(new Date()),
        date_time: (new Date(util.formatTime(new Date())).getTime()) / 1000,
        status: 0
      }
      let pro = JSON.stringify(arr)
      // console.log(pro)
      util.postAjax(app.globalData.apiUrl +'/admin_add_community_health_expert_tall',function(res){
        // console.log(res)
        if(res.data == 1){
          util.showToast('提交成功','success',2000)
          if(that.data.type == '1'){
            wx.navigateTo({
              url: '/subPages/mine/consultList/consultList?type=' + 3,
            })
            flag = false
          }else if(that.data.type == '2'){
            wx.navigateBack({
              delta: 1, // 回退前 delta(默认为1) 页面
            })
            flag = false
          }
        }else{
          flag = false
          util.showToast('提交失败，请重试','none',2000)
        }
      },{pro: pro})
    }
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})